﻿using System.Collections.Generic;
using System.Threading.Tasks;
namespace Odyssey.Consul.Implementations
{
    using Features;
    using Http;
    using Models;

    public class Session : BaseConsulAPI, ISession
    {
        public Session(IHttpRequester httpRequester, IConsulConfiguration consulConfiguration) : base(httpRequester, consulConfiguration, EnumResource.Session)
        {
        }

        private string BuildSessionPath(string action)
        {
            return BuildUri("session", action);
        }

        private QueryParameter BuildQueryParameter(ArguSession arguSession)
        {
            QueryParameter queryParameter = null;
            if (arguSession != null && string.IsNullOrWhiteSpace(arguSession.DC))
            {
                queryParameter.Datacenter = arguSession.DC;
            }
            return queryParameter;
        }

        public async Task<ResultSessionCreate> Create(ArguSession arguSession)
        {
            return await ApiSend<object, ResultSessionCreate>(BuildSessionPath("create"), new
            {
                arguSession.LockDelay,
                arguSession.Node,
                arguSession.Name,
                arguSession.Checks,
                arguSession.Behavior,
                arguSession.TTL
            }, queryParameter: BuildQueryParameter(arguSession));
        }

        public async Task<bool> Delete(ArguSession arguSession)
        {
            return (await ApiSendString(BuildSessionPath($"destroy/{arguSession.ID}"), queryParameter: BuildQueryParameter(arguSession))).Contains("true");
        }

        public async Task<List<ResultSession>> Read(ArguSession arguSession)
        {
            return await ApiSend<List<ResultSession>>(BuildSessionPath($"info/{arguSession.ID}"), queryParameter: BuildQueryParameter(arguSession));
        }

        public async Task<List<ResultSession>> ListForNode(ArguSession arguSession)
        {
            return await ApiSend<List<ResultSession>>(BuildSessionPath($"node/{arguSession.Node}"), queryParameter: BuildQueryParameter(arguSession));
        }

        public async Task<List<ResultSession>> List(ArguSession arguSession)
        {
            return await ApiSend<List<ResultSession>>(BuildSessionPath("list"), queryParameter: BuildQueryParameter(arguSession));
        }

        public async Task<List<ResultSession>> Renew(ArguSession arguSession)
        {
            return await ApiSend<List<ResultSession>>(BuildSessionPath($"renew/{arguSession.ID}"), queryParameter: BuildQueryParameter(arguSession));
        }
    }
}
